<?php
/**
 * 通话详单
 */
namespace app\admin\model;
use think\Db;
use app\admin\model\Common;
use think\cache\driver\Redis;

class Call extends Common
{
    public function getRelationInfo($relation){
        $info = [
            'father'=>"父亲",
            'mother'=>"母亲",
            'spouse'=>"配偶",
            'brother'=>"兄弟",
            'sister'=>"姐妹",
            'children'=>"子女",
            'friend'=>"朋友",
            'colleague'=>"同事",
            'other'=>"其他"
        ];
        return $info[$relation];
    }

    /**
     * 获取通话详单
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-05T14:54:25+0800
     * @param    int     $uid   用户id
     * @return   array   数据
     */
    // public function getTelDetails($uid='')
    // {
    //     $where['uid']          = $uid;
    //     $res                   = Db::name('user_info')->where($where)->field('operator_outUniqueId,mongo_operator_report')->find();     //同盾通讯报告
    //     $outUniqueId           = $res['operator_outUniqueId'];     //同盾通讯报告
    //     $mongo_operator_report = $res['mongo_operator_report'];    //mogodb id
    //     $tel_address           = Db::name('user_tel_address')->where($where)->value('tel_address_list');  //本地通讯录
    //     $four_contacts         = array();
    //     $ten_contacts          = array();
    //     $phone_four            = array();
    //     $phone_ten             = array();
    //     $phone_four_ten        = array();
    //     $result                = array();
    //     $data = array(
    //         'list'=>[],      //通讯录列表
    //         'dataCount'=>0,  //通讯录总数
    //         'matchCount'=>0  //匹配总数
    //     );

    //     try{
    //         $secret_about  = Db::name('secret_about')->where($where)->find();   //天机数据
    //         $four_contacts = json_decode($secret_about['four_contacts'], true); //四个紧急联系人
    //         $ten_contacts  = explode('-', $secret_about['ten_contacts']);       //前十联系人
    //         foreach ($four_contacts as $key => $value) {
    //             $four_contacts[$key]['match'] = 2;
    //             $four_contacts[$key]['type'] = '4';//紧急联系人
    //             $four_contacts[$key]['relation'] = $this->getRelationInfo($four_contacts[$key]['relation']);
    //             unset($four_contacts[$key]['no']);
    //             $phone_four[] = $four_contacts[$key]['phone'];
    //         }

    //         foreach ($ten_contacts as $key => $value) {
    //             $ten_contacts[$key] = [];
    //             $ten_contacts[$key]['name'] = '';
    //             $ten_contacts[$key]['phone'] = $value;
    //             $ten_contacts[$key]['match'] = 2;
    //             $ten_contacts[$key]['type'] = '2';//前十联系人
    //             $k = array_search($value, $phone_four);
    //             if($k!==false){
    //                 $ten_contacts[$key] = $four_contacts[$k];
    //                 $ten_contacts[$key]['type'] = '6';//紧急+前十联系人
    //                 $phone_four_ten[] = $ten_contacts[$key]['phone']; 
    //             }
    //             $phone_ten[] = $ten_contacts[$key]['phone'];
    //         }
    //     } catch (\Exception $e) {
    //         $four_contacts = array();
    //         $ten_contacts  = array();
    //     }

    //     try {
    //         $tel_address = json_decode(unserialize($tel_address),true);
    //         foreach ($tel_address as $key => $value) {
    //             $result[$key]['name']  = $value['displayName'];
    //             $result[$key]['match'] = 2;  //是否存在运营商通话详单中 0:否  1:是  2:未获取通话详单
    //             $result[$key]['phone'] = ''; //本地通讯录号码
    //             $result[$key]['type']  = '1'; //本地联系人
    //             $result[$key]['relation'] = ''; //关系
    //             foreach ($value['phoneNumbers'] as $k => $v) {
    //                 $result[$key]['phone'] = $this->format_phone($v['value']); 
    //                 $k = array_search($result[$key]['phone'], $phone_four); 
    //                 if($k!==false){
    //                     $result[$key]['type'] = '5';//紧急+本地联系人
    //                     $result[$key]['relation'] = $four_contacts[$k]['relation'];
    //                     $result[$key]['name'] = $four_contacts[$k]['name'];
    //                 }
    //                 $k2 = array_search($result[$key]['phone'], $phone_ten);
    //                 if($k2!==false){
    //                     $result[$key]['type'] = '3';//前十+本地联系人
    //                     $result[$key]['relation'] = $ten_contacts[$k2]['relation'];
    //                     // $result[$key]['name'] = $ten_contacts[$k2]['name'];
    //                     $k3 = array_search($result[$key]['phone'], $phone_four_ten);
    //                     if($k3!==false){
    //                         $result[$key]['type'] = '7';//紧急+前十+本地联系人
    //                         $result[$key]['relation'] = $ten_contacts[$k2]['relation'];
    //                         $result[$key]['name'] = $ten_contacts[$k2]['name'];
    //                     }
    //                 }
    //             }
    //         }
    //     } catch (\Exception $e) {
    //         $result = array();
    //     }

    //     # 合并
    //     $result = array_merge_recursive($result, $ten_contacts);
    //     $result = array_merge_recursive($result, $four_contacts); 

    //     if(!empty($result)){
    //         # 重排数组 
    //         foreach ($result as $key => $value) {
    //             $type[$key]  = $value['type'];
    //         }
    //         array_multisort($type, SORT_DESC, $result);
    //         # 去重
    //         $result = $this->array_unique_fb($result);
    //     }

    //     // 读取数据
    //     $count = 0;
    //     if($mongo_operator_report){
    //         # 读取mongodb数据
    //         $mongo = Db::connect("db_mongo")->name('yueguangbaika')->where("_id",$mongo_operator_report)->find();
    //         $mongo = $mongo['stringdata'];
    //         $list = json_decode($mongo,true);
    //     }else if($outUniqueId){
    //         # 读取redis数据
    //         $redis = new Redis();
    //         $list = $redis ->select(10);         //选择10号库
    //         $list = $redis ->get($outUniqueId);  //获取运营商通话详单，注：线上才能获取 
    //         if(!$list){
    //             $list = $redis ->select(16);         //选择16号库
    //             $list = $redis ->get($outUniqueId);  //获取运营商通话详单，注：线上才能获取
    //         }
    //     }

    //     // 处理数据
    //     if($list){
    //         # 获取到数据
    //         foreach ($list['call_log'] as $k => $v) {
    //             $list[$k] = $v['phone'];
    //         }
    //         foreach ($result as $k => $v) {
    //             $phone = $result[$k]['phone'];
    //             if(in_array($phone, $list)){ 
    //                 $result[$k]['match'] = 1; 
    //                 $count = $count +1;
    //             }else{
    //                 $result[$k]['match'] = 0; 
    //             }
    //         }
    //     }
    //     // else{
    //     //     # 未获取到redis或者mongodb数据则将授权清空，需要用户重新获取
    //     //     $param['operator_outUniqueId'] = null;
    //     //     $param['mongo_operator_report'] = null;
    //     //     $param['operator_state'] = null;
    //     //     $param['operator_search_id'] = null;
    //     //     $param['operator_id'] = null;
    //     //     $param['operator_state2'] = null;
    //     //     $param['operator_account'] = null;
    //     //     db('user_info')->where($where)->update($param);
    //     // }

    //     $data['list']       = $result;
    //     $data['dataCount']  = count($result);
    //     $data['matchCount'] = $count;
    //     return $data;
    // }


  
   /**
    * 功能:     用户通讯录
    * @Author   Mrzhp
    * @email    18702529695@163.com
    * @DateTime 2018-02-06
    * @param    [type]              $uid [description]
    * @return   [type]                   [description]
    */
   public function getTelDetails($uid)
   {
      $local_url = $_SERVER['SERVER_NAME'];
      $url = 'http://'.$local_url.'/admin/Scriptfile/report_split?uid='.$uid;
      $this->httpGet($url);
      $mongodb_qqtb_id =  Db::name('user_info')->where(['uid'=>$uid])->value('mongodb_qqtb_id');
      $res = Db::connect("db_mongo")->name('yueguangbaika')->where("_id",$mongodb_qqtb_id)->find();
    
      // 通话清单
      $mongodb_call_log_id =  Db::name('report_call')->where(['uid'=>$uid])->value('mongodb_call_log_id');
      $res_call_log = Db::connect("db_mongo")->name('yueguangbaika')->where("_id",$mongodb_call_log_id)->find();


      $res_call_log = json_decode($res_call_log['call_log_data'],true);

      $qqtb_data = $res['qqtb_data'];

      $qqtb_data =  json_decode($qqtb_data,true);
      if(!is_array($qqtb_data)){
        $qqtb_data =  json_decode($qqtb_data,true);
      }
      

    /**
     * 通讯录匹配
     */
 
   $call_log = array();
   foreach($res_call_log as $key1=>$call_value)
   {
       $v = strtotime($call_value['last_contact_date']);
       $call_log[$v] = $call_value['phone'];

   }

   $i = 0;
   foreach($qqtb_data as $key=>$qqtb_value)
   {
          
           $phone = str_replace('-','',$qqtb_value['phone']);
           
           if(in_array($phone,$call_log))
           {
               $last_contact_date =  array_search($phone,$call_log);
               if($last_contact_date > (time()-(180*24*60*60)))
               {
                 
                 $i++;
                 $qqtb_data[$key]['match'] = 1;

               }else{

                  $qqtb_data[$key]['match'] = 0;

               }
                  

           }else{

                $qqtb_data[$key]['match'] = 0;

           }
               
         


    }
    
     if($i>=15)
     {

        Db::name('report_call')->where(['uid'=>$uid])->update(['is_fifteen'=>1]);
     }

      $count = count($qqtb_data);
      if(!$qqtb_data){

          return false;

      }

     // if($type==1)
     // {
     //    return $i;
     // }else{
          $qqtb_data = $this->arraySequence($qqtb_data,'match');
          $data['dataCount'] = $count;
          $data['list'] = $qqtb_data;
          return $data;
     // }
          

   }



  /**
 * 二维数组根据字段进行排序
 * @params array $array 需要排序的数组
 * @params string $field 排序的字段
 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
public function arraySequence($array, $field, $sort = 'SORT_DESC')
{
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;
}




/**
 * curl get请求
 * @param  [type] $url [description]
 * @return [type]      [description]
 */    
    public  function httpGet($url) 
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
     
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }







    /**
     * 格式化手机号码
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-29T14:24:54+0800
     * @param    string     $phone   手机号
     * @return   string                         
     */
    public function format_phone($phone) {
        $phone = preg_replace("/[^0-9]/", "", $phone);  //去除非数字字符
        if(strlen($phone) == 13) {
            $phone = str_replace('86', '', $phone);     //去掉86字段 例如：8618888888888
        }
        return $phone;
    }

    //二维数组去掉重复值 
    public function array_unique_fb($array){
        $result = array();
        foreach ($array as $key => $value) {
            $has = false;
            foreach($result as $val){
                if($val['phone'] == $value['phone']){
                    $has = true;
                    break;
                }
            }
            if(!$has){
                $result[] = $value;
            }      
        }
        return $result;
    }

}
